<template>
  <div>
    <cusDialog :title="userForm.id ? '人员编辑' : '人员添加'" ref="dialog" width="450px" headCss="float:left;"
      @hideHandler="hideHandler" @confrim="confrimHandler">
      <el-form :model="userForm" ref="userFormRef" :rules="rules" label-width="100">

        <el-form-item label="用户头像:" prop="headPortrait">
          <cus-uploadImg :img="userForm.headPortrait ? [userForm.headPortrait] : []" @success="handleSuccess"
            @delete="handlerDelete"></cus-uploadImg>
        </el-form-item>
        <el-form-item label="姓名：" prop="name">
          <el-input v-model.trim="userForm.name" maxlength="30" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="登录账号：" prop="loginName">
          <el-input v-model.trim="userForm.loginName" maxlength="30" placeholder="请输入登录账号"
            :disabled="userForm.id ? true : false"></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" prop="phoneNumber">
          <el-input v-model.trim="userForm.phoneNumber" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="单位名称：">
          <el-input v-model.trim="userForm.departmentName" maxlength="30" placeholder="请输入单位"></el-input>
        </el-form-item>
        <el-form-item label="职务：">
          <el-input v-model.trim="userForm.postName" maxlength="30" placeholder="请输入职务"></el-input>
        </el-form-item>
        <el-form-item label="所属角色：">
          <el-checkbox-group v-model="roleIdList" @change="handleChange">
            <el-checkbox v-for="item in roleList" :key="item.name" :label="item.id">{{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="默认密码：">
          12345
        </el-form-item>
        <el-form-item label-width="20">
          <el-checkbox v-model="userForm.appScope" label="授权登录小程序" />
        </el-form-item>
      </el-form>

    </cusDialog>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { reqRoleList } from "@/api/business/role";
import {
  reqAddUser,
  reqModifyUserInfo,
  reqUserInfo,
  reqAssignRole,
  upUserAvatar
} from "@/api/business/user";
import { useUserStoreHook } from "@/store/modules/user";
const router = useRouter();
const userStore = useUserStoreHook();



const formOrigin = () => ({
  name: "",
  loginName: "",
  phoneNumber: "",
  departmentName: "",
  postName: "",
  password: "12345",
  appScope: "",
  id: "",
  headPortrait: '',
});
// 用户角色列表
const roleIdList = ref([]);

const emits = defineEmits<{
  (event: "onInit"): void;
}>();

const userForm = ref(formOrigin());
const userFormRef = ref(null);
const rules = reactive<FormRules>({
  name: { required: true, message: "姓名不能为空", trigger: "blur" },
  loginName: [
    { required: true, message: "登录账号不能为空", trigger: "blur" },
    {
      pattern: "^[a-zA-Z0-9]{5,10}$",
      message: "请输入合法的5-10位字母与数字",
      trigger: "blur",
    },
  ],
  phoneNumber: {
    required: false,
    pattern: "^(0[0-9]{2,3}-[0-9]{7,8})$|^1[3456789][0-9]{9}$",
    message: "手机/电话号码格式不正确",
    trigger: "blur",
  },
  headPortrait: {
    required: true,
    message: "请上传头像图片",
    trigger: "blur",
  },
});

const dialog = ref(null);
const handleChange = (v) => {
  console.log("选中数", v);
};
const show = (id) => {
  if (id) {
    userForm.value.id = id;
    getUserInfo();
  }
  dialog.value.show = true;
  getRoleList();
};

// 头像上传成功
const handleSuccess = (url) => {
  userForm.value.headPortrait = url
  console.log(url,)
}

// 删除用户头像
const handlerDelete = () => {
  userForm.value.headPortrait = ''
}

// 获取用户信息
const getUserInfo = () => {
  reqUserInfo({ id: userForm.value.id }).then((res) => {
    if (res.code === 1) {
      userForm.value = res.data.base;
      userForm.value.appScope = Boolean(userForm.value.appScope)
      roleIdList.value = res.data.list;
    }
  });
};

// 角色列表
const roleList = ref([]);

// 请求角色列表
const getRoleList = () => {
  reqRoleList().then((res) => {
    if (res.code === 1) {
      roleList.value = res.data.list;
    }
    console.log(res);
  });
};

// 对话框关闭重置初始数据
const hideHandler = () => {
  userForm.value = formOrigin();
  userFormRef.value.resetFields();
  roleIdList.value = [];
};

// 添加用户
const getAddUser = () => {
  userForm.value.appScope = Number(userForm.value.appScope)
  reqAddUser({ ...userForm.value }).then((res) => {
    if (res.code === 1) {
      let userId = res.data;
      getAssignRole(res.data).then(() => {
        emits("onInit");
        ElMessage.success("添加成功");
        dialog.value.show = false;

      })
    } else {
      ElMessage.info(res.msg);
    }
  });
};
// 修改用户信息
const getModifyUserInfo = () => {
  delete userForm.value.password;
  userForm.value.appScope = Number(userForm.value.appScope)
  reqModifyUserInfo({ ...userForm.value, }).then((res) => {
    if (res.code === 1) {
      getAssignRole(userForm.value.id).then(() => {
        ElMessage.success("修改成功");
        emits("onInit");
        dialog.value.show = false;
        if (userStore.pinia_userInfo.baseInfo.id == userForm.value.id) {
          ElMessageBox.confirm(
            "您修改了当前用户信息,需要刷新页面才可生效,是否立即刷新?"
          )
            .then(() => {
              window.location.reload();
            })
        }

      })
    } else {
      ElMessage.info(res.msg);
    }
  });
};
const getAssignRole = (id) => {
  return new Promise((resolve, reject) => {
    reqAssignRole({ userId: id, roleList: roleIdList.value }).then((res) => {
      if (res.code === 1) {
        resolve()
      } else {
        ElMessage.info(res.msg);
      }
    });

  })
}
const confrimHandler = () => {
  userFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (userForm.value.id) {
        getModifyUserInfo();
      } else {
        getAddUser();
      }
    } else {
      ElMessage.info("请检查表单内容");
    }
  });
};

defineExpose({ show });
</script>

<style lang="scss" scoped></style>